package com.camera.yl.dialog

import android.content.Context
import android.os.Bundle
import android.view.WindowManager
import android.widget.Button
import android.widget.NumberPicker
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import com.camera.yl.R

class NumberPickerDialog(context: Context, private val title: String, private val options: Array<String>, private val onSelectListener: (Int) -> Unit, private val widthPercent:Int = 80) : AlertDialog(context) {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val dialogWidth = calculateDialogWidth()

        setContentView(R.layout.custom_dialog)

        val layoutParams = WindowManager.LayoutParams()
        layoutParams.copyFrom(window!!.attributes)
        layoutParams.width = dialogWidth // 设置宽度为300dp

        window!!.attributes = layoutParams

        val titleTextView = findViewById<TextView>(R.id.titleTextView)
        titleTextView!!.text = title

        val numberPicker = findViewById<NumberPicker>(R.id.numberPicker)
        numberPicker.apply {
            this!!.minValue = 0
            this!!.maxValue = options.size - 1
            this!!.displayedValues = options
            this!!.wrapSelectorWheel = true
        }

        val cancelButton = findViewById<Button>(R.id.cancelButton)
        cancelButton!!.setOnClickListener { dismiss() }

        val okButton = findViewById<Button>(R.id.okButton)
        okButton!!.setOnClickListener {
            val selectedValue = numberPicker!!.value
            onSelectListener(selectedValue)
            dismiss()
        }
    }
    private fun calculateDialogWidth(): Int {
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val display = windowManager.defaultDisplay
        val width = display.width // 获取屏幕宽度
        return width * widthPercent / 100
    }
}